<?php

namespace App\Http\Controllers\Backend;

use App\Http\Requests\Backend\EditUserRole;
use App\Http\Requests\Backend\StoreUserRole;
use App\Http\Resources\Backend\UserRoleResource;
use App\Models\AdminLog;
use App\Models\UserRole;
use Illuminate\Http\Request;

/**
 * Class UserRoleController
 * @package App\Http\Controllers\Backend
 */
class UserRoleController extends BackendController
{
    /**
     * @param Request $request
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
     * 用户角色列表
     */
    public function index(Request $request)
    {
        $userRole = UserRole::orderBy('created_at', 'desc')
            ->nameLike($request->name)
            ->schoolIs($request->school_id)
            ->with('school')
            ->paginate($request->size);
        return UserRoleResource::collection($userRole);
    }

    /**
     * @param StoreUserRole $request
     * @return UserRoleResource
     * 新增用户角色
     */
    public function store(StoreUserRole $request)
    {
        if (UserRole::where('school_id', $request->school_id)->doesntExist()) {
            $isDefault = UserRole::IS_DEFAULT;
        } else {
            $isDefault = UserRole::NOT_DEFAULT;
        }
        $userRole = new UserRole();
        $userRole->fill($request->all());
        $userRole->is_default = $isDefault;
        $userRole->save();
        AdminLog::log('新增用户角色: ' . $userRole->name);
        return new UserRoleResource($userRole);
    }

    /**
     * @param EditUserRole $request
     * @param UserRole $userRole
     * @return UserRoleResource
     * 编辑角色
     */
    public function update(EditUserRole $request, UserRole $userRole)
    {
        $userRole->fill(\request()->all());
        $userRole->save();
        AdminLog::log('编辑用户角色: ' . $userRole->name);
        return new UserRoleResource($userRole);
    }

    /**
     * @param $id
     * @return array
     * 更改默认角色
     */
    public function destroy($id)
    {
        $model = UserRole::findOrFail($id);
        $role = UserRole::where([['is_default', UserRole::IS_DEFAULT], ['school_id', $model->school_id]])->first();
        if ($role) {
            $role->is_default = UserRole::NOT_DEFAULT;
            $role->save();
        }
        $model->is_default = UserRole::IS_DEFAULT;
        if ($model->save()) {
            AdminLog::log($model->name . '取消默认角色');
            return $this->success();
        }
        return $this->fail('取消失败');
    }
}
